Completed
Push — master ( d0de5b...5e0518 )
by Vitaly
30s
created

stacktracey.js ➔ ... ➔ ???

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
nc 16
nop 2
dl 0
loc 4
1
"use strict";
2
3
/*  ------------------------------------------------------------------------ */
4
5
const O            = Object,
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name Object as O. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
6
      isBrowser    = (typeof window !== 'undefined') && (window.window === window) && window.navigator,
7
      lastOf       = x => x[x.length - 1],
8
      getSource    = require ('get-source'),
9
      partition    = require ('./impl/partition'),
10
      asTable      = require ('as-table')
11
12
/*  ------------------------------------------------------------------------ */
13
14
class StackTracey extends Array {
15
16
    constructor (input, offset) {
17
        
18
        const originalInput          = input
19
            , isParseableSyntaxError = input && (input instanceof SyntaxError && !isBrowser)
20
        
21
        super ()
22
23
    /*  Fixes for Safari    */
24
25
        this.constructor = StackTracey
26
        this.__proto__   = StackTracey.prototype
27
28
    /*  new StackTracey ()            */
29
30
        if (!input) {
31
             input = new Error ()
32
             offset = (offset === undefined) ? 1 : offset
33
        }
34
35
    /*  new StackTracey (Error)      */
36
37
        if (input instanceof Error) {
38
            input = input[StackTracey.stack] || input.stack || ''
39
        }
40
41
    /*  new StackTracey (string)     */
42
43
        if (typeof input === 'string') {
44
            input = StackTracey.rawParse (input).slice (offset).map (StackTracey.extractEntryMetadata)
45
        }
46
47
    /*  new StackTracey (array)      */
48
49
        if (Array.isArray (input)) {
50
51
            if (isParseableSyntaxError) {
52
                
53
                const rawLines = module.require ('util').inspect (originalInput).split ('\n')
54
                    , fileLine = rawLines[0].match (/^([^:]+):(.+)/)
55
56
                input.unshift ({
57
                    file: fileLine && fileLine[1],
58
                    line: fileLine && fileLine[2],
59
                    column: rawLines[2].indexOf ('^'),
60
                    sourceLine: rawLines[1],
61
                    callee: '(syntax error)',
62
                    syntaxError: true
63
                })
64
            }
65
66
            this.length = input.length
67
            input.forEach ((x, i) => this[i] = x)
68
        }
69
    }
70
71
    static extractEntryMetadata (e) {
72
        
73
        const fileRelative = StackTracey.relativePath (e.file)
74
75
        return O.assign (e, {
76
77
            calleeShort:  e.calleeShort || lastOf (e.callee.split ('.')),
78
            fileRelative: fileRelative,
79
            fileShort:    StackTracey.shortenPath (fileRelative),
80
            fileName:     lastOf (e.file.split ('/')),
81
            thirdParty:   StackTracey.isThirdParty (fileRelative) && !e.index
82
        })
83
    }
84
85
    static shortenPath (relativePath) {
86
        return relativePath.replace (/^node_modules\//, '')
87
                           .replace (/^webpack\/bootstrap\//, '')
88
    }
89
90
    static relativePath (fullPath) {
91
        return fullPath.replace (isBrowser ? window.location.href : (process.cwd () + '/'), '')
92
                       .replace (/^.*\:\/\/?\/?/, '')
93
    }
94
95
    static isThirdParty (relativePath) {
96
        return (relativePath[0] === '~')                          || // webpack-specific heuristic
97
               (relativePath[0] === '/')                          || // external source
98
               (relativePath.indexOf ('node_modules')      === 0) ||
99
               (relativePath.indexOf ('webpack/bootstrap') === 0)
100
    }
101
102
    static rawParse (str) {
103
104
        const lines = (str || '').split ('\n')
105
106
        const entries = lines.map (line => { line = line.trim ()
107
108
            var callee, fileLineColumn = [], native, planA, planB
0 ignored issues
show
Unused Code introduced by
The assignment to variable fileLineColumn seems to be never used. Consider removing it.
Loading history...
109
110
            if ((planA = line.match (/at (.+) \((.+)\)/)) ||
111
                (planA = line.match (/(.*)@(.*)/))) {
112
113
                callee         =  planA[1]
114
                native         = (planA[2] === 'native')
115
                fileLineColumn = (planA[2].match (/(.*):(.+):(.+)/) || []).slice (1) }
116
117
            else if ((planB = line.match (/^(at\s+)*(.+):([0-9]+):([0-9]+)/) )) {
118
                fileLineColumn = (planB).slice (2) }
119
120
            else {
121
                return undefined }
122
123
            return {
124
                beforeParse: line,
125
                callee:      callee || '',
126
                index:       isBrowser && (fileLineColumn[0] === window.location.href),
127
                native:      native || false,
128
                file:        fileLineColumn[0] || '',
129
                line:        parseInt (fileLineColumn[1] || '', 10) || undefined,
130
                column:      parseInt (fileLineColumn[2] || '', 10) || undefined } })
131
132
        return entries.filter (x => (x !== undefined))
133
    }
134
135
    withSource (i) {
136
        return this[i] && StackTracey.withSource (this[i])
137
    }
138
139
    static withSource (loc) {
140
141
        if (loc.sourceFile || (loc.file && loc.file.indexOf ('<') >= 0)) { // skip things like <anonymous> and stuff that was already fetched
142
            return loc }
143
144
        else {
145
            let resolved = getSource (loc.file).resolve (loc)
146
147
            if (resolved.sourceFile) {
148
                resolved.file = resolved.sourceFile.path
149
                resolved = StackTracey.extractEntryMetadata (resolved)
150
            }
151
152
            if (resolved.sourceLine && resolved.sourceLine.includes ('// @hide')) {
153
                resolved.sourceLine  = resolved.sourceLine.replace  ('// @hide', '')
154
                resolved.hide = true
155
            }
156
157
            return O.assign ({ sourceLine: '' }, loc, resolved)
158
        }
159
    }
160
161
    get withSources () {
162
        return new StackTracey (this.map (StackTracey.withSource))
163
    }
164
165
    get mergeRepeatedLines () {
166
        return new StackTracey (
167
            partition (this, e => e.file + e.line).map (
168
                group => {
169
                    return group.items.slice (1).reduce ((memo, entry) => {
170
                        memo.callee      = (memo.callee      || '<anonymous>') + ' → ' + (entry.callee      || '<anonymous>')
171
                        memo.calleeShort = (memo.calleeShort || '<anonymous>') + ' → ' + (entry.calleeShort || '<anonymous>')
172
                        return memo }, O.assign ({}, group.items[0])) }))
173
    }
174
175
    get clean () {
176
        return this.withSources.mergeRepeatedLines.filter ((e, i) => (i === 0) || !(e.thirdParty || e.hide))
177
    }
178
179
    at (i) {
180
        return O.assign ({
181
182
            beforeParse: '',
183
            callee:      '<???>',
184
            index:       false,
185
            native:      false,
186
            file:        '<???>',
187
            line:        0,
188
            column:      0
189
190
        }, this[i])
191
    }
192
193
    static locationsEqual (a, b) {
194
        return (a.file   === b.file) &&
195
               (a.line   === b.line) &&
196
               (a.column === b.column)
197
    }
198
199
    get pretty () {
200
201
        return asTable (this.withSources.map (
202
                            e => [  ('at ' + e.calleeShort.slice (0, 30)),
203
                                    (e.fileShort && (e.fileShort + ':' + e.line)) || '',
204
                                    ((e.sourceLine || '').trim () || '').slice (0, 80)      ]))
205
    }
206
207
    static resetCache () {
208
209
        getSource.resetCache ()
210
    }
211
212
    get asArray () {
213
214
    }
215
}
216
217
/*  Chaining helper for .isThirdParty
218
    ------------------------------------------------------------------------ */
219
220
(() => {
221
222
    const methods = {
223
224
        include (pred) {
225
226
            const f = StackTracey.isThirdParty
227
            O.assign (StackTracey.isThirdParty = (path => f (path) ||  pred (path)), methods)
228
        },
229
230
        except (pred) {
231
232
            const f = StackTracey.isThirdParty
233
            O.assign (StackTracey.isThirdParty = (path => f (path) && !pred (path)), methods)
234
        },
235
    }
236
237
    O.assign (StackTracey.isThirdParty, methods)
238
239
}) ()
240
241
/*  Array methods
242
    ------------------------------------------------------------------------ */
243
244
;['map', 'filter', 'slice', 'concat', 'reverse'].forEach (name => {
245
246
    StackTracey.prototype[name] = function (/*...args */) { // no support for ...args in Node v4 :(
247
        
248
        const arr = Array.from (this)
249
        return new StackTracey (arr[name].apply (arr, arguments))
250
    }
251
})
252
253
/*  A private field that an Error instance can expose
254
    ------------------------------------------------------------------------ */
255
256
StackTracey.stack = (typeof Symbol !== 'undefined') ? Symbol.for ('StackTracey') : '__StackTracey'
0 ignored issues
show
Bug introduced by
The variable Symbol seems to be never declared. If this is a global, consider adding a /** global: Symbol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
257
258
/*  ------------------------------------------------------------------------ */
259
260
module.exports = StackTracey
261
262
/*  ------------------------------------------------------------------------ */
263
264